import { Inject, Injectable } from '@nestjs/common';
import { RegisterUserDto } from './dto/register-user.dto';
import { PrismaService } from './middleware/prisma/prisma.service';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';
import { SvgService } from './middleware/svg/svg.service';
import { RedisService } from './middleware/redis/redis.service';
import { EmailService } from './middleware/email/email.service';

@Injectable()
export class UserService {
  @Inject(PrismaService)
  private prismaService: PrismaService;

  @Inject(JwtService)
  jwtService: JwtService;

  @Inject(SvgService)
  private svgService: SvgService;

  @Inject(RedisService)
  private redisService: RedisService;

  @Inject(EmailService)
  private emailService: EmailService;

  async login(loginUserDto: LoginUserDto) {
    if (!(loginUserDto.code === '888888')) {
      return '验证码错误';
    }

    const foundUser = await this.prismaService.user.findFirst({
      where: {
        account: loginUserDto.account,
      },
    });

    if (!foundUser) {
      return '用户不存在';
    }

    if (foundUser.password !== loginUserDto.password) {
      return '密码错误';
    }

    delete foundUser.password;
    delete foundUser.isDetele;

    const secret = 'hh2837183';

    return {
      foundUser,
      token: this.jwtService.sign(
        {
          userId: foundUser.id,
          username: foundUser.username,
        },
        {
          secret: secret,
          expiresIn: '7d',
        },
      ),
    };
  }

  async register(registerUser: RegisterUserDto) {
    if (!(registerUser.code === '888888')) {
      return '验证码错误';
    }
    // 自动生成账号 唯一id
    const table = await this.prismaService.user.findMany();
    const account = `HH${(table.length + 1).toString().padStart(5, '0')}`;

    // 自动生成默认账号头像
    const avatarURL = 'http://localhost:9000/dev/err.png';

    try {
      return await this.prismaService.user.create({
        data: {
          account: account,
          username: registerUser.username,
          nickName: registerUser.nickName,
          password: registerUser.password,
          avatarURL: avatarURL,
          email: registerUser.email,
          phone: registerUser.phone,
        },
        select: {
          id: true,
          account: true,
          username: true,
          nickName: true,
          gender: true,
          avatarURL: true,
          email: true,
          phone: true,
          isAdmin: true,
          status: true,
          role: true,
          createTime: true,
        },
      });
    } catch (e) {
      return null;
    }
  }

  async loginSvg() {
    return await this.svgService.sendSvg();
  }

  async registerEmail(email: string) {
    const code = Math.random().toString().slice(2, 8);

    await this.redisService.set(`email_${email}`, code, 5 * 60);

    await this.emailService.sendMail({
      to: email,
      subject: '注册验证码',
      html: `<p>你的注册验证码是 ${code}</p>`,
    });
    return '邮件验证码发送成功';
  }

  async list() {
    const pageSize = 10;
    const pageNum = 1;
    const user = await this.prismaService.user.findMany({
      skip: (Number(pageNum) - 1) * Number(pageSize),
      take: Number(pageSize),
      where: {
        isDetele: '1',
      },
      select: {
        id: true,
        account: true,
        username: true,
        nickName: true,
        gender: true,
        avatarURL: true,
        email: true,
        phone: true,
        isAdmin: true,
        status: true,
        role: true,
        createTime: true,
        updateTime: true,
      },
    });

    const result = {
      list: user,
      pageNum: Number(pageNum),
      pageSize: Number(pageSize),
      total: user.length,
    };
    return result;
  }
}
